from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import ListView
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from app.models import ToolInfo
from app.forms import ToolForm


def tool_list(request):
    """用户列表展示"""
    tools = ToolInfo.objects.all()
    return render(request, 'tools/tool_list.html', {'tools': tools})


def tool_add(request):
    """添加工具"""
    if request.method == 'POST':
        form = ToolForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('tool_list')
    else:
        form = ToolForm()
    return render(request, 'tools/tool_add.html', {'form': form})


def tool_edit(request, tool_id):
    """编辑工具"""
    tool = get_object_or_404(ToolInfo, id=tool_id)
    if request.method == 'POST':
        form = ToolForm(request.POST, instance=tool)
        if form.is_valid():
            form.save()
            return redirect('user_list')
    else:
        form = ToolForm(instance=tool)
    return render(request, 'tools/tool_edit.html', {'form': form, 'tool': tool})


def tool_delete(request, tool_id):
    """删除用户"""
    tool = get_object_or_404(ToolInfo, id=tool_id)
    tool.delete()
    return redirect('tool_list')
